// pages/paymentCode/goThrough/index.js
const app = getApp()
var call = require("../../../utils/request.js");
const {
  barcode,
  qrcode
} = require('../../../utils/index.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    refreshStatus: true, // 刷新状态
    currentData: 0,
    payCode: '', //付款码
    userInfo: {},
    timeIndex: 0,
    counts: 50,
    open: true,
    timer: null, // 判断二维码状态
    timer2: null, // 判断到1分钟刷新一次二维码
    timer3: null, // 秒钟
    success: false,
    err: false,
    errHint: '',
    count: 5,
    time: '',
    qrcode: '',
    navListData: [{
      id: 1,
      img: '/image/home/nav01.png',
      name: '疫情填报'
    }, {
      id: 2,
      img: '/image/home/nav02.png',
      name: '企业名单'
    }, {
      id: 3,
      img: '/image/home/nav03.png',
      name: '导航'
    }, {
      id: 4,
      img: '/image/home/nav04.png',
      name: '来访人员'
    }, {
      id: 5,
      img: '/image/home/nav05.png',
      name: '停车缴费'
    }, {
      id: 6,
      img: '/image/home/nav06.png',
      name: '通讯录'
    }, {
      id: 7,
      img: '/image/home/nav07.png',
      name: '信息公开'
    }, {
      id: 8,
      img: '/image/home/nav08.png',
      name: '企业认证'
    }],
    countTimer: null,
    goThroughBg: '/image/public/goThroughBg.png', //背景图
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let goThroughBg = wx.getFileSystemManager().readFileSync(this.data.goThroughBg, 'base64'); //背景图转义

    wx.cloud.init()
    let userInfo = wx.getStorageSync('userInfo');
    let currentPark = wx.getStorageSync('currentPark')
    console.log(userInfo);
    this.setData({
      goThroughBg: 'data:image/jpg;base64,' + goThroughBg,
      userInfo,
      currentPark
    });
    this.getCode()
    setTimeout(() => {
      this.onload()
      this.setTimer()
    }, 2000);
    this.getTime()
    // this.timer();
  },
  // 点击导航
  goNav() {

  },
  // 未开放功能
  Public() {
    wx.showToast({
      icon: 'none',
      title: '加紧施工中...',
    })
  },
  // 获取时间  并且每秒刷新
  getTime() {
    let timer3 = setInterval(() => {
      let date = new Date()
      let time = this.timestampToTime(date.toLocaleString('en-US', {
        hour12: false
      }).split(" "))
      this.setData({
        time
      })
    }, 1000)
    this.setData({
      timer3
    })
  },

  timestampToTime(times) {
    let time = times[1]
    let mdy = times[0]
    mdy = mdy.split('/')
    let month = parseInt(mdy[0]);
    let day = parseInt(mdy[1]);
    let year = parseInt(mdy[2])
    return year + '.' + month + '.' + day + ' ' + time
  },


  // 获取二维码
  async getCode(flag) {
    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      "path": "/v1/door",
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    console.log(code, data, errorMsg, '通行码');
    if (code == 1) {
      if (flag) {
        this.setData({
          success: false,
          refreshStatus: false
        })
        setTimeout(() => {
          this.setData({
            refreshStatus: true
          })
        }, 1000)
      }
      qrcode('qrcode', data, 430, 430);
      this.setData({
        qrcode: data
      })
    } else {
      wx.showToast({
        title: errorMsg,
        icon: 'none'
      })
    }
  },
  // 验证通行码使用状态
  setTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.setData({
        timer: null
      })
    }
    console.log('设置定时器');
    let timer = setInterval(() => {
      wx.cloud.callContainer({
        "config": {
          "env": "prod-0g38oh8hf0e4d5ac"
        },
        "path": "/v1/door/" + this.data.qrcode,
        "header": {
          "X-WX-SERVICE": "springboot-069k"
        },
        "method": "get",
        "data": {
          "action": "inc"
        }
      }).then(res => {

        let {
          errorCode,
          errorInfo,
          isSuccess
        } = res.data.data
        console.log(errorCode, errorInfo, isSuccess,this.data.qrcode,'发送请求');
        
        if (isSuccess == 1) {
          console.log('已开门');
          if (this.data.timer) {
            clearInterval(this.data.timer)
            this.setData({
              timer: null
            })
          }
          this.setData({
            success: true
          })
        } else if (isSuccess == -1) {
          console.log('还没使用');
        } else {
          console.log(errorCode);
          if (errorCode == 'Q999') {
            
          } else if (errorCode == 'Q000') {
            console.log('已开门');
            if (this.data.timer) {
              clearInterval(this.data.timer)
              this.setData({
                timer: null
              })
            }
            this.setData({
              success: true
            })
          } else if (errorCode == 'Q002') {
            this.removeTimer()
            this.setData({
              err: true,
              count: 5,
              errHint: '暂无权限，请咨询前台客服'
            })
            let countTimer = setInterval(() => {
              let count = this.data.count - 1
              this.setData({
                count
              })
              console.log(this.data.count);
              if (this.data.count == 0) {
                console.log('返回');
                if (this.data.countTimer) {
                  console.log('清空定时器');
                  clearInterval(this.data.countTimer)
                  this.setData({
                    countTimer: null
                  })
                }
                this.back()
              }
            }, 1000)
            this.setData({
              countTimer
            })
          } else if (errorCode == 'Q003') {
            this.removeTimer()
            this.setData({
              err: true,
              count: 5,
              errHint: '二维码已失效，请点击返回刷新'
            })
            let countTimer = setInterval(() => {
              let count = this.data.count - 1
              this.setData({
                count
              })
              console.log(this.data.count);
              if (this.data.count == 0) {
                console.log('返回');
                if (this.data.countTimer) {
                  console.log('清空定时器');
                  clearInterval(this.data.countTimer)
                  this.setData({
                    countTimer: null
                  })
                }
                this.back()
              }
            }, 1000)
            this.setData({
              countTimer
            })
          } else {
            this.removeTimer()
            this.setData({
              err: true,
              count: 5,
              errHint: '验证失败，请咨询前台客服'
            })
            let countTimer = setInterval(() => {
              let count = this.data.count - 1
              this.setData({
                count
              })
              console.log(this.data.count);
              if (this.data.count == 0) {
                console.log('返回');
                if (this.data.countTimer) {
                  console.log('清空定时器');
                  clearInterval(this.data.countTimer)
                  this.setData({
                    countTimer: null
                  })
                }
                this.back()
              }
            }, 1000)
            this.setData({
              countTimer
            })

          }
        }
      })
    }, 2000)
    this.setData({
      timer
    })
  },
  // 重新获取二维码 重新打开50s定时器 2s的轮询检测
  back() {
    if (this.data.countTimer) {
      clearInterval(this.data.countTimer)
      this.setData({
        countTimer: null
      })
    }
    this.setData({
      err: false
    })
    this.getCode()
    this.onload()
    this.setTimer()
  },
  // 设置定时器
  onload() {
    if (this.data.timer2) {
      clearInterval(this.data.timer2)
      this.setData({
        timer2: null
      })
    }
    let timer2 = setInterval(() => {
      this.getCode(true)
      this.setTimer()
    }, 50000)
    this.setData({
      timer2
    })
    
  },

  removeTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.setData({
        timer: null
      })
    }
    if (this.data.timer2) {
      clearInterval(this.data.timer2)
      this.setData({
        timer2: null
      })
    }
  },



  webSocket() {
    // 创建Socket 
    wx.connectSocket({
      // 192.168.100.233:8099
      url: 'wss://socket.199.nuomayun.com:8099/pay/5f0d456078d004lfy04/' + this.data.userInfo.id,
      header: {
        'content-type': 'application/json',
      },
      timeout: 5000, //超时时间，单位为毫秒
      success: (e) => { //接口调用成功的回调函数
        console.log(e, '创建Websocket 连接成功')
      },
      fail: (e) => { //接口调用失败的回调函数
        console.log(e, '失败')
      }
    })
    wx.onSocketOpen(res => {
      let set = setInterval(() => {
        if (this.data.open == true) {
          wx.sendSocketMessage({
            data: 'getPayCode',
            success: (e) => {
              this.setData({
                open: false
              })
            }
          })
        }
      }, 10)
    })
    wx.onSocketMessage((e) => {
      let data = JSON.parse(e.data);
      console.log(data)
      if (data.actionName == '付款码') {
        let payCode = JSON.parse(e.data).data.payCode;
        if (payCode) {
          this.setData({
            refreshStatus: false
          })
          setTimeout(() => {
            this.setData({
              refreshStatus: true
            })
          }, 1000)
        } else {
          wx.showToast({
            icon: 'none',
            title: '刷新失败'
          })
        }
        barcode('barcode', payCode, 600, 150);
        qrcode('qrcode', payCode, 462, 462);
      } else {
        wx.showToast({
          icon: 'none',
          title: data.data.title,
          duration: 5000,
          icon: 'success',
        });
        this.setData({
          open: true
        })
      }
    })
  },
  // 刷新二维码
  refresh() {
    // this.setData({
    //   open: true
    // });
    this.getCode(true)
    this.onload()
    this.setTimer()
  },
  onHide() {
    console.log('隐藏');
    // var that = this;
    // clearInterval(that.data.timeIndex);
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.setData({
        timer: null
      })
    }
    if (this.data.timer2) {
      clearInterval(this.data.timer2)
      this.setData({
        timer2: null
      })
    }
    if (this.data.timer3) {
      clearInterval(this.data.timer3)
      this.setData({
        timer3: null
      })
    }
  },
  onUnload() {
    console.log('卸载');
    // var that = this;
    // clearInterval(that.data.timeIndex);
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.setData({
        timer: null
      })
    }
    if (this.data.timer2) {
      clearInterval(this.data.timer2)
      this.setData({
        timer2: null
      })
    }
  },
  //定时器
  // timer() {
  //   var that = this;
  //   that.data.timeIndex = setInterval(function () {
  //     var times = --that.data.counts;
  //     that.setData({
  //       counts: times
  //     });
  //     if (that.data.counts < 1) {
  //       that.setData({
  //         counts: 50,
  //         open: true
  //       });
  //     }
  //   }, 1000);
  // },
  //获取当前滑块的index
  bindchange: function (e) {
    const that = this;
    console.log(e.detail.current)
    that.setData({
      currentData: e.detail.current
    })
  },
  // 禁止滑动
  catchTouchMove: function (res) {
    return false
  },
  // 点击切换，滑块index赋值
  checkCurrent: function (e) {
    const that = this;
    if (e.target.dataset.current == 1) {
      wx.showToast({
        icon: 'none',
        title: '功能暂未开放',
      })
      return false;
    }
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current
      })
    }
  },
  // 预览二维码
  previewImage(e) {
    let as = this
    let canvasId = e.currentTarget.dataset.name;
    wx.canvasToTempFilePath({
      canvasId,
      fileType: 'jpg',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(res);
        wx.previewImage({
          current: tempFilePath, // 当前显示图片的http链接  
          urls: [tempFilePath] // 需要预览的图片http链接列表  
        })
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // onUnload() {
  //   wx.closeSocket();
  //   clearInterval(this.data.timeIndex);
  // }
})